import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/base_dialog.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../tools/widgets/my_button.dart';
import '../../utils/toast_utils.dart';
import '../login/login_router.dart';
import '../my/setting_router.dart';
import 'model/Device.dart';


class DeviceSettingPage extends StatefulWidget {
  const DeviceSettingPage({
    super.key,
    this.deviceId,
    this.type,
    this.isShare,
    this.deviceName,
  });

  final int? deviceId;
  final int? type;
  final int? isShare;
  final String? deviceName;


  @override
  State<DeviceSettingPage> createState() => _DeviceSettingPageState();
}

class _DeviceSettingPageState extends State<DeviceSettingPage> {
  final DeviceApi _deviceApi = DeviceApi();
  late int _type;
  late int _isShare;

  late String _statusText;
  late Color _statusColor;
  late String _deviceName;
  late int _deviceId;
  Device? _device;

  @override
  void initState() {
    super.initState();
    _deviceName = widget.deviceName!;
    _deviceId = widget.deviceId!;
    _type = widget.type ?? 1;
    _isShare = widget.isShare ?? 1;

    _statusText = _type == 0 ? AppLocale.text('h_lixian') : AppLocale.text('h_zaixian');
    _statusColor = _type == 0 ? Colors.grey : Colors.green;

    _fetchData();
  }



  Future<void> _fetchData() async {
    try {
      final response = await _deviceApi.getDeviceInfo(_deviceId);
      if (response.code == 200) {
        setState(() {
          _device = Device.fromJson(response.data);
        });
      } else {
        AppLocale.text('s_500');
      }
    } catch (e) {
      AppLocale.text('s_get500');;
    }
  }


  Future<void> _updateDevice(String deviceName) async {
    final deviceToUpdate = {
      "deviceId": _deviceId,
      "deviceName": deviceName,
    };
    final response = await _deviceApi.updateDevice(deviceToUpdate);
    if (response.code == 200) {
      setState(() {
        _deviceName = deviceName;
      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_shebeishezhi'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),

      // 使用SingleChildScrollView允许内容滚动
      body: SingleChildScrollView(
        // 处理键盘弹出时的padding
        child: Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          child: Column(
            children: [
              // 主要内容区域
              Column(
                children: [
                  const SizedBox(height: 20,),

                  // 左侧文字+图标，右侧文字+图片
                  ItemView(
                    width: 400,
                    height: 80,
                    leftPadding: 10,
                    rightPadding: 15,
                    leftWidget: Row(
                      children: [
                        Image.asset(() {
                          switch (_device?.deviceType) {
                            case 1:
                              return "images/images/add/q1.png";
                            case 2:
                              return "images/images/add/q2.png";
                            case 3:
                              return "images/images/add/q3.png";
                            case 4:
                              return "images/images/add/q4.png";
                            default:
                              return "images/images/add/q1.png"; // 默认图（未加载或类型不符时）
                          }
                        }(), // 注意：匿名函数需要加 () 执行并返回结果
                          width: 40,
                          errorBuilder: (context, error, stackTrace) {
                            return Image.asset("images/images/add/q1.png", width: 40); // 加载失败默认图
                          },
                        ),
                        const SizedBox(width: 8),
                        // 移除了所有 const 关键字
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(_deviceName), // 移除了 const
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                CircleAvatar(radius: 6, backgroundColor: _statusColor),
                                const SizedBox(width: 8),
                                Text(
                                  _statusText,
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                    color: _statusColor,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        )
                      ],
                    ),
                    rightWidget: Row(
                      children: [
                        const SizedBox(width: 8),
                        Image.asset("images/images/deviceSetting/a1.png", width: 25),
                      ],
                    ),
                    borderRadius: 10,
                    onTap: () {
                      BrnMiddleInputDialog(
                          title: AppLocale.text('d_xiugaishebeiming'),
                          hintText: _deviceName,
                          cancelText: AppLocale.text('cancel'),
                          confirmText: AppLocale.text('confirm'),
                          autoFocus: true,
                          maxLength: 1000,
                          maxLines: 2,
                          //只允许数字
                          // inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                          dismissOnActionsTap: false,
                          barrierDismissible: true,
                          onConfirm: (value) {
                            _updateDevice(value);
                            Navigator.pop(context);
                          },
                          onCancel: () {
                            Navigator.pop(context);
                          }).show(context);
                    },
                  ),


                  const SizedBox(height: 10,),

                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s1.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_shebeixinxi'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceInfoPage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),
                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s2.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_banbengengxin'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceVersionPage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),


                  const SizedBox(height: 10,),

                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s3.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_baojindhezhi'),),
                      ],
                    ),
                    borderRadius: 8,
                    showLine: true,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceAlarmPage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),
                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    showLine: true,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s4.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_bendicunchu'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceStoragePage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),

                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    rightPadding: 20,
                    showLine: true,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s5.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_zhiliansuoshrzhi'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceLockPage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),

                  ItemView(
                    width: 400,
                    height: 60,
                    leftPadding: 20,
                    showLine: true,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s6.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_duijiangshezhi'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceIntercomPage}?deviceId=$_deviceId&device=$encodedDevice',
                        );
                      }
                    },
                  ),

                  ItemView(
                    width: 400,
                    showLine: true,
                    height: 60,
                    leftPadding: 20,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        Image.asset("images/images/deviceSetting/s7.png", width: 24),
                        const SizedBox(width: 10),
                        Text(AppLocale.text('d_genduoshezhi'),),
                      ],
                    ),
                    borderRadius: 8,
                    onTap: () {
                      if (_device != null) {
                        final deviceJson = json.encode(_device!.toJson());
                        final encodedDevice = Uri.encodeComponent(deviceJson);
                        NavigatorUtils.push(
                          context,
                          '${XDeviceRouter.deviceMorePage}?deviceId=$_deviceId&isShare=$_isShare&device=$encodedDevice',
                        );
                      }
                    },
                  ),
                ],
              ),

              // 底部按钮区域，增加足够的间距
              // SizedBox(height: MediaQuery.of(context).size.height * 0.1),

              // 固定下方按钮
              Padding(
                padding: const EdgeInsets.all(30),
                child: SafeArea(
                  child: MyButton(
                    radius: 10,
                    minWidth: double.infinity,
                    text: AppLocale.text('d_yichushebei'),
                    onPressed: (){
                      BrnDialogManager.showConfirmDialog(context,
                          title: AppLocale.text('d_yichushebei'),
                          cancel: AppLocale.text('cancel'),
                          confirm: AppLocale.text('confirm'),
                          message: AppLocale.text('d_yichushebeiData'),
                          onConfirm: () async {
                            // 显示加载对话框
                            showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (context) => Center(
                                child: Container(
                                  width: 80,
                                  height: 80,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: const Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      CircularProgressIndicator(),
                                    ],
                                  ),
                                ),
                              ),
                            );

                            try {
                              final response = await _deviceApi.deleteById(_deviceId)
                                  .timeout(const Duration(seconds: 10));

                              Navigator.pop(context); // 关闭加载对话框

                              if(response.code == 200){
                                Toast.show(AppLocale.text('d_yichushebeichenggong'));
                                Navigator.pop(context);
                                await Future.delayed(const Duration(seconds: 1));
                                Navigator.pushNamed(context, "/home");
                              }else{
                                Toast.show(AppLocale.text('d_yichushebeishibai') + "，${response.msg ?? ''}");
                              }
                            } catch (e) {
                              Navigator.pop(context); // 关闭加载对话框
                              Toast.show(AppLocale.text('d_chaoshihuosheibai'));
                            }
                          },
                          onCancel: () {
                            Navigator.pop(context);
                          }
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
